﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace d1Project.Tools.Baidu
{
    //信息推送工具
    public  class BaiduPushHelper
    {
        public static BaiduPushHelper Instance = new BaiduPushHelper();

        const string Method = "push_msg";
        const string Url = "http://channel.api.duapp.com/rest/2.0/channel/channel";

        string appkey;
        string masterSecret;
        public BaiduPushHelper()
            : this("", "")
        {

        }
        public BaiduPushHelper(string appkey, string masterSecret)
        {
            this.appkey = appkey;
            this.masterSecret = masterSecret;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="pushOs">Android IOS</param>
        public async Task<string> SendMessage(string pushOs, string pushId, string title, string content, string tag, int count = 1)
        {
            if (!pushId.Contains("_"))
            {
                return "推送ID错误";
            }
            if (pushOs == "Android")
            {
                appkey = "57UhXluuDY3w0FkM7PAkziAh";
                masterSecret = "gj2HQlvFeiRcWnTwcNrmE63Qhygof5MN";
            }
            else
            {
                appkey = "VRX22ScFxNnigd94xH69nwPC";
                masterSecret = "YqXtjeEanwbobxaZihz578drGMpt5Sy4";
            }
            var spt = pushId.Split('_');
            var dic = BuildDictionary(pushOs, appkey, masterSecret, spt[0], spt[1], title, content, tag);
            using (HttpClient client = new HttpClient())
            {
                var response = await client.PostAsync(Url, new FormUrlEncodedContent(dic));
                if (response.IsSuccessStatusCode)
                {
                    return "成功";
                }
                var result = await response.Content.ReadAsStringAsync();
                string res = JObject.Parse(result)["error_msg"].ToString();
                return res;
            }
        }

        public async Task<string> SendMessageToList(List<string> pushId, string pushOs, string title, string content, string tag, int count = 1)
        {
            List<string> errorList = new List<string>();
            using (HttpClient client = new HttpClient())
            {
                foreach (var item in pushId)
                {
                    if (!item.Contains("_"))
                    {
                        errorList.Add(item + ":推送ID错误");
                        continue;
                    }
                    var spt = item.Split('_');
                    var dic = BuildDictionary(pushOs, appkey, masterSecret, spt[0], spt[1], title, content, tag);
                    var response = await client.PostAsync(Url, new FormUrlEncodedContent(dic));
                    if (!response.IsSuccessStatusCode)
                    {
                        var result = await response.Content.ReadAsStringAsync();
                        var errorMessage = JObject.Parse(result)["error_msg"].ToString();
                        errorList.Add(item + ":" + errorMessage);
                    }
                }
            }
            if (errorList.Count > 0)
            {
                return "失败";
            }
            return "成功";
        }

        static Dictionary<string, string> BuildDictionary(string pushOs, string apiKey, string secretKey, string userId, string channelId, string title, string content, string tag)
        {
            Dictionary<string, string> parmsDic = new Dictionary<string, string>();
            parmsDic.Add("apikey", apiKey);
            parmsDic.Add("channel_id", channelId);
            if (pushOs == "Android")
            {
                parmsDic.Add("device_type", "3");
            }
            else if (pushOs == "IOS")
            {
                parmsDic.Add("device_type", "4");
            }
            parmsDic.Add("message_type", "1");
            if (pushOs == "Android")
            {
                parmsDic.Add("messages", "{\"title\":\"" + title + "\",\"description\":\"" + content + "\",\"notification_builder_id\":0,\"notification_basic_style\":7,\"open_type\":0,\"url\":\"\",\"user_confirm\":0,\"pkg_content\":\"\",\"custom_content\":{\"tag\":\"" + HttpUtility.JavaScriptStringEncode(tag) + "\"}}");
            }
            else
            {
                parmsDic.Add("messages", "{\"aps\":{\"alert\":\"" + content + "\",\"sound\":\"\",\"badge\":1},\"tag\":\"" + HttpUtility.JavaScriptStringEncode(tag) + "\"}");
            }
            //\"custom_content\":{\"tag\":\"" + HttpUtility.JavaScriptStringEncode(tag) + "\",
            //\"title\":\"" + title + "\",\"description\":\"" + content + "\",
            //parmsDic.Add("messages", "{\"title\":\"" + title + "\",\"description\":\"" + content + "\",\"notification_builder_id\":0,\"notification_basic_style\":7,\"open_type\":0,\"url\":\"\",\"user_confirm\":0,\"pkg_content\":\"\",\"custom_content\":{\"tag\":\"" + HttpUtility.JavaScriptStringEncode(tag) + "\"}}");
            parmsDic.Add("method", "push_msg");
            parmsDic.Add("msg_keys", Guid.NewGuid().ToString("N"));
            parmsDic.Add("push_type", "1");
            TimeSpan ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
            uint unixTime = (uint)ts.TotalSeconds;
            parmsDic.Add("timestamp", unixTime.ToString());
            parmsDic.Add("user_id", userId);
            parmsDic.Add("v", "1");
            //按要求拼接字符串，并urlencode编码
            var str = HttpUtility.UrlEncode("POST" + Url + string.Concat(parmsDic.Keys.Zip(parmsDic.Values, (k, v) => k + "=" + v)) + secretKey, System.Text.Encoding.UTF8);
            var strSignUpper = new StringBuilder();
            int perIndex = 0;
            for (int i = 0; i < str.Length; i++)
            {
                var c = str[i].ToString();
                if (str[i] == '%')
                {
                    perIndex = i;
                }
                if (i - perIndex == 1 || i - perIndex == 2)
                {
                    c = c.ToUpper();
                }
                strSignUpper.Append(c);
            }
            strSignUpper = strSignUpper.Replace("(", "%28").Replace(")", "%29");
            var sign = BaiduPushHelper.GetMd5(strSignUpper.ToString());

            //加入生成好的sign键值对
            parmsDic.Add("sign", sign);
            return parmsDic;
        }

        static string GetMd5(string data)
        {
            MD5 md5 = MD5.Create();
            byte[] retVal = md5.ComputeHash(Encoding.Default.GetBytes(data));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return sb.ToString();
        }
    }
}